import classnames from 'classnames'
import { useHistory } from 'react-router'
import { NavBar, SearchBar } from 'antd-mobile'

import Icon from '@/components/Icon'
import styles from './index.module.scss'
import { useState } from 'react'
import {useDebounceFn} from 'ahooks'
import { useDispatch, useSelector } from 'react-redux'
import { getSuggestion, addSearchList } from '@/store/actions/search'
import { RootState } from '@/types/store'
import highLight from '@/utils/highLight'

const SearchPage = () => {
  const history = useHistory()
  const dispatch = useDispatch()

  const [keyword, setKeyword] = useState('')
  const [isSearching, setIsSearching] = useState(false)

  const {run} = useDebounceFn((value) => {
    if (!value) {
      return
    }
    dispatch(getSuggestion(value))
  }, {
    wait: 500
  })

  const {suggestion, history: historyList} = useSelector((state: RootState) => state.search)

  const onChange = (value: string) => {
    setKeyword(value)
    if (value) {
      setIsSearching(true)
    } else {
      setIsSearching(false)
    }
    run(value)
  }

  const onSearch = (keyword: string) => {
    if (!keyword) {
      return
    }
    // 添加的历史记录不予许重复，把原先的历史记录删除掉，再添加
    const newHistoryList = historyList.filter(i => i !== keyword)
    newHistoryList.unshift(keyword)
    //历史记录不能超过10条
    if (newHistoryList.length > 10) {
      newHistoryList.pop()
    }
    dispatch(addSearchList(newHistoryList))
    // 跳转页面
    history.push('/search/result?key=' + keyword)
  }

  const onDelHistory = (keyword: string) => {
    const newHistoryList = historyList.filter(i => i !== keyword)
    dispatch(addSearchList(newHistoryList))
  }

  const onClearHistory = () => {
    dispatch(addSearchList([]))
  }

  return (
    <div className={styles.root}>
      <NavBar
        className="navbar"
        onBack={() => history.go(-1)}
        right={
          <span
            className="search-text"
            onClick={() => {
              onSearch(keyword)
            }}
          >搜索</span>}
      >
        <SearchBar
          placeholder="请输入关键字搜索"
          value={keyword}
          onChange={onChange}
        />
      </NavBar>

      {true && (
        <div
          className="history"
          style={{
            display: isSearching ? 'none' : 'block'
          }}
        >
          <div className="history-header">
            <span>搜索历史</span>
            <span onClick={onClearHistory}>
              <Icon type="iconbtn_del"/>
              清除全部
            </span>
          </div>

          <div className="history-list">
            {
              historyList.map((item, index) => (
                <span key={index} className="history-item">
                  <span className="text-overflow">{item}</span>
                  <Icon type="iconbtn_essay_close" onClick={() => {
                    onDelHistory(item)
                  }}/>
                </span>
              ))
            }
          </div>
        </div>
      )}

      <div className={classnames('search-result', isSearching ? 'show' : '')}>
        {
          suggestion.map((item, index) => (
            <div
              key={index}
              className="result-item"
              onClick={() => {
                onSearch(item)
              }}
            >
              <Icon className="icon-search" type="iconbtn_search" />
              <div
                className="result-value text-overflow"
                dangerouslySetInnerHTML={{
                  __html: highLight(item, keyword)
                }}
              >
              </div>
            </div>
          ))
        }
      </div>
    </div>
  )
}

export default SearchPage
